package com.xbongbong.paas.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.field.ItemPoJo;
import com.xbongbong.paas.pojo.CallTaskLogCountPojo;
import com.xbongbong.paas.pojo.dto.CallSearchItemsDTO;
import com.xbongbong.paas.pojo.dto.CallTaskLogBatchDeleteDTO;
import com.xbongbong.paas.pojo.dto.CallTaskLogCountDTO;
import com.xbongbong.paas.pojo.dto.CallTaskLogDeleteDTO;
import com.xbongbong.paas.pojo.dto.CallTaskLogFindNextPhoneDTO;
import com.xbongbong.paas.pojo.dto.CallTaskLogListDTO;
import com.xbongbong.paas.pojo.dto.CallTaskSaveDTO;
import com.xbongbong.paas.pojo.dto.FeeRemainDTO;
import com.xbongbong.paas.pojo.vo.CallSearchItemsVO;
import com.xbongbong.paas.pojo.vo.CallTaskLogBatchDeleteVO;
import com.xbongbong.paas.pojo.vo.CallTaskLogCountListVO;
import com.xbongbong.paas.pojo.vo.CallTaskLogCountVO;
import com.xbongbong.paas.pojo.vo.CallTaskLogDeleteVO;
import com.xbongbong.paas.pojo.vo.CallTaskLogFindNextPhoneVO;
import com.xbongbong.paas.pojo.vo.CallTaskLogVO;
import com.xbongbong.paas.pojo.vo.FeeRemainVO;
import com.xbongbong.paas.service.XbbCallTaskLogService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.helper.PageHelper;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.pro.constant.I18nStringConstant;
import com.xbongbong.pro.enums.ErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.CallCenterErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.CustomerErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.saas.constant.XbbCallTaskLogConstant;
import com.xbongbong.saas.domain.entity.CallTaskEntity;
import com.xbongbong.saas.domain.entity.CallTaskLogEntity;
import com.xbongbong.saas.domain.entity.ext.ContactEntityExt;
import com.xbongbong.saas.domain.entity.ext.CustomerEntityExt;
import com.xbongbong.saas.enums.CallStatusEnum;
import com.xbongbong.saas.enums.business.ContactEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.enums.dictionary.DictionaryEnum;
import com.xbongbong.saas.model.ContactModel;
import com.xbongbong.saas.model.CustomerModel;
import com.xbongbong.saas.model.XbbCallTaskLogModel;
import com.xbongbong.saas.model.XbbCallTaskModel;
import com.xbongbong.saas.service.ContactService;
import com.xbongbong.saas.service.CustomerService;
import com.xbongbong.saas.service.DictionaryService;
import com.xbongbong.sys.domain.entity.FeeEntity;
import com.xbongbong.sys.domain.entity.FeeLogEntity;
import com.xbongbong.sys.model.FeeLogModel;
import com.xbongbong.sys.model.FeeModel;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * @author youli.chen
 * @version v1.0
 * @description: 呼叫中心批量外呼计划日志实现类
 * @date 2019/2/23 16:48
 * @since v1.0
 */
@Service("xbbCallTaskLogService")
public class XbbCallTaskLogServiceImpl implements XbbCallTaskLogService {

    @Resource
    private FeeModel feeModel;
    @Resource
    private FeeLogModel feeLogModel;
    @Resource
    private CustomerModel customerModel;
    @Resource
    private ContactModel contactModel;
    @Resource
    private XbbCallTaskLogModel xbbCallTaskLogModel;
    @Resource
    private XbbCallTaskModel xbbCallTaskModel;
    @Resource
    private CustomerService customerService;
    @Resource
    private ContactService contactService;
    @Resource
    private DictionaryService dictionaryService;

    /**
     * 批量新增外呼日志
     *
     * @param corpid          公司ID
     * @param callTaskId      呼叫中心批量外呼计划ID
     * @param callTaskSaveDTO 呼叫中心批量外呼计划
     * @throws XbbException 销帮帮设定的异常
     */
    @Override
    public void batchSave(String corpid, Long callTaskId, CallTaskSaveDTO callTaskSaveDTO) throws XbbException {
        // 客户外呼日志批量新增
        if (callTaskSaveDTO.getCustomerIdList() != null) {
            List<CustomerEntityExt> customerExtList = customerService.getCustomerListByIds(corpid, callTaskSaveDTO.getCustomerIdList());
            List<CallTaskLogEntity> callTaskLogList = new ArrayList<>();
            if (customerExtList.size() != 0) {
                for (CustomerEntityExt customerEntityExt : customerExtList) {
                    if (customerEntityExt.getData() == null) {
                        throw new XbbException(CustomerErrorCodeEnum.API_ERROR_201001);
                    } else {
                        CallTaskLogEntity callTaskLogEntity = new CallTaskLogEntity();
                        callTaskLogEntity.setCorpid(corpid);
                        callTaskLogEntity.setCallTaskId(callTaskId);
                        callTaskLogEntity.setCustomerId(customerEntityExt.getId());
                        callTaskLogEntity.setType(customerEntityExt.getData().getInteger(CustomerManagementEnum.TYPE.getAttr()));
                        String cusPhone = customerEntityExt.getData().getString(CustomerManagementEnum.PHONE.getAttr());
                        callTaskLogList.add(callTaskLogPhone(cusPhone, callTaskLogEntity));
                    }
                }
                try {
                    xbbCallTaskLogModel.batchInsert(callTaskLogList);
                } catch (Exception e) {
                    throw new XbbException(CallCenterErrorCodeEnum.API_ERROR_301078);
                }
            }
            // 联系人外呼日志批量新增
        } else if (callTaskSaveDTO.getContactIdList() != null) {
            List<ContactEntityExt> contactExtList = contactService.getContactListByIds(corpid, callTaskSaveDTO.getContactIdList());
            List<CallTaskLogEntity> callTaskLogList = new ArrayList<>();
            if (contactExtList.size() != 0) {
                for (ContactEntityExt contactEntityExt : contactExtList) {
                    if (contactEntityExt.getData() == null) {
                        throw new XbbException(CustomerErrorCodeEnum.API_ERROR_201001);
                    } else {
                        CallTaskLogEntity callTaskLogEntity = new CallTaskLogEntity();
                        callTaskLogEntity.setCorpid(corpid);
                        callTaskLogEntity.setCallTaskId(callTaskId);
                        callTaskLogEntity.setCustomerId(contactEntityExt.getData().getLong(ContactEnum.CUSTOMER_NAME.getAttr()));
                        callTaskLogEntity.setContactId(contactEntityExt.getId());
                        String contactPhone = contactEntityExt.getData().getString(ContactEnum.PHONE.getAttr());
                        callTaskLogList.add(callTaskLogPhone(contactPhone, callTaskLogEntity));
                    }
                }
                try {
                    xbbCallTaskLogModel.batchInsert(callTaskLogList);
                } catch (Exception e) {
                    throw new XbbException(CallCenterErrorCodeEnum.API_ERROR_301078);
                }
            }
        }
    }

    /**
     * 业务层 获取每个通话状态对应的总条数
     *
     * @param callTaskLogCountDTO 获取每个通话状态对应的总条数入参
     * @return CallTaskLogCountVO 批量外呼每个通话状态对应的总条数 API 返回数据
     * @throws XbbException 销帮帮设定的异常
     */
    @Override
    public XbbResponse<CallTaskLogCountVO> countStatusByTaskId(CallTaskLogCountDTO callTaskLogCountDTO) throws XbbException {
        Map<String, Object> params = new LinkedHashMap<>();
        params.put("corpid", callTaskLogCountDTO.getCorpid());
        params.put("callTaskId", callTaskLogCountDTO.getCallTaskId());
        params.put("countStatus", "allUse");
        params.put("del", DelEnum.NORMAL.getDel());
        List<CallTaskLogEntity> taskLogEntList = xbbCallTaskLogModel.findEntitys(params);
        CallTaskLogCountVO countVO = new CallTaskLogCountVO();
        if (taskLogEntList != null) {
            countVO = taskLogCountMsg(taskLogEntList);
        }
        return new XbbResponse<>(countVO);
    }

    /**
     * 业务层 获取每个通话状态对应的总条数列表
     *
     * @param corpid       公司ID
     * @param callTaskIdIn 呼叫中心批量外呼计划ID队列
     * @return CallTaskLogCountListVO 批量外呼每个通话状态对应的总条数 API 列表返回数据
     * @throws XbbException 销帮帮设定的异常
     */
    @Override
    public CallTaskLogCountListVO countStatusListByTaskIds(String corpid, List<Long> callTaskIdIn) throws XbbException {
        Map<String, Object> params = new LinkedHashMap<>();
        params.put("corpid", corpid);
        params.put("callTaskIdIn", callTaskIdIn);
        params.put("countStatus", "allUse");
        params.put("del", DelEnum.NORMAL.getDel());
        List<CallTaskLogEntity> taskLogEntList = xbbCallTaskLogModel.findEntitys(params);
        if (taskLogEntList.size() == 0) {
            throw new XbbException(CallCenterErrorCodeEnum.API_ERROR_301079);
        }
        List<CallTaskLogEntity> taskLog = new ArrayList<>();

        CallTaskLogCountListVO callTaskLogMsg = new CallTaskLogCountListVO();
        List<CallTaskLogCountPojo> pojoList = new ArrayList<>();
        CallTaskLogCountPojo countPojo = new CallTaskLogCountPojo();
        CallTaskLogCountVO countVO;
        LinkedHashMap<Long, CallTaskLogCountVO> taskLogCount = new LinkedHashMap<>();

        List<Long> taskLogTaskIdIn = new ArrayList<>();
        for (CallTaskLogEntity taskLogEntity : taskLogEntList) {
            taskLogTaskIdIn.add(taskLogEntity.getCallTaskId());
            // 去重
            LinkedHashSet<Long> set = new LinkedHashSet<>(taskLogTaskIdIn);
            set.addAll(taskLogTaskIdIn);
            taskLogTaskIdIn.clear();
            taskLogTaskIdIn.addAll(set);
        }
        for (Long callTaskId : taskLogTaskIdIn) {
            for (CallTaskLogEntity taskLogEntity : taskLogEntList) {
                if (Objects.equals(taskLogEntity.getCallTaskId(), callTaskId)) {
                    taskLog.add(taskLogEntity);
                }
            }
            countVO = taskLogCountMsg(taskLog);
            taskLogCount.put(callTaskId, countVO);
            countPojo.setTaskLogCountList(taskLogCount);
            pojoList.add(countPojo);
            callTaskLogMsg.setCallTaskLogCountListVO(pojoList);
        }
        return callTaskLogMsg;
    }

    /**
     * 业务层 获取剩余批量外呼条数
     *
     * @param feeRemainDTO 获取剩余批量外呼条数入参
     * @return FeeRemainVO 获取剩余批量外呼条数 返回数据
     * @throws XbbException 销帮帮设定的异常
     */
    @Override
    public FeeRemainVO getRemain(FeeRemainDTO feeRemainDTO) throws XbbException {
        FeeRemainVO feeRemainVO = new FeeRemainVO();
        String corpid = feeRemainDTO.getCorpid();
        Map<String, Object> param = new HashMap<>(16);
        param.put("del", DelEnum.NORMAL.getDel());
        // 支付完成
        param.put("isPay", 1);
        // 批量外呼套餐
        param.put("feeType", 3);
        param.put("corpid", corpid);
        param.put("orderByStr", "update_time DESC");
        List<FeeLogEntity> feeLogEntityList = feeLogModel.findEntitys(param);
        BigDecimal feeCount = BigDecimal.ZERO;
        HashMap<Long, BigDecimal> feeIdAndFeeCount = new HashMap<>(16);
        if (feeLogEntityList.size() != 0) {
            List<Long> feeIdIn = new ArrayList<>();
            LinkedHashMap<Long, Integer> feeIdAndBuyNum = new LinkedHashMap<>();
            for (FeeLogEntity feeLogEntity : feeLogEntityList) {
                Long feeId = feeLogEntity.getFeeId();
                feeIdIn.add(feeId);
                Integer buyNum = feeIdAndBuyNum.get(feeId);
                Integer logBuyNum = feeLogEntity.getBuyNum() == null ? Integer.valueOf(0) : feeLogEntity.getBuyNum();
                if (buyNum == null) {
                    feeIdAndBuyNum.put(feeId, logBuyNum);
                } else {
                    buyNum += logBuyNum;
                    feeIdAndBuyNum.put(feeId, buyNum);
                }
            }

            //去重
            LinkedHashSet<Long> set = new LinkedHashSet<>(feeIdIn);
            set.addAll(feeIdIn);
            feeIdIn.clear();
            feeIdIn.addAll(set);
            List<FeeEntity> feeEntityList = feeModel.getFeeListByIdIn(feeIdIn);
            HashMap<Long, Integer> idAndUserNum = new HashMap<>(16);
            for (FeeEntity feeEntity : feeEntityList) {
                idAndUserNum.put(feeEntity.getId(), feeEntity.getPrimaryNum());
            }

            Set<Map.Entry<Long, Integer>> entrySet = feeIdAndBuyNum.entrySet();
            Iterator<Map.Entry<Long, Integer>> feeIdAndBuyNumList = entrySet.iterator();
            while (feeIdAndBuyNumList.hasNext()) {
                Map.Entry<Long, Integer> me = feeIdAndBuyNumList.next();
                Long feeId = me.getKey();
                BigDecimal buyNum = BigDecimal.ZERO;
                if (feeIdAndBuyNum.get(feeId) != null) {
                    buyNum = new BigDecimal(feeIdAndBuyNum.get(feeId));
                }
                BigDecimal userNum = BigDecimal.ZERO;
                if (idAndUserNum.get(feeId) != null) {
                    userNum = new BigDecimal(idAndUserNum.get(feeId));
                }
                BigDecimal msg = buyNum.multiply(userNum);
                // 每个充值日志对应的充值条数 youli.chen
                feeIdAndFeeCount.put(feeId, msg);
                feeCount = feeCount.add(msg);
            }
        }

        Map<String, Object> params = new HashMap<>(16);
        params.put("del", DelEnum.NORMAL.getDel());
        params.put("corpid", corpid);
        params.put("countStatus", "allUse");
        BigDecimal taskLogCount = BigDecimal.valueOf(xbbCallTaskLogModel.getEntitysCount(params));

        BigDecimal getRemain = feeCount.subtract(taskLogCount);
        feeRemainVO.setFeeIdAndFeeCount(feeIdAndFeeCount);
        feeRemainVO.setGetRemain(getRemain);
        return feeRemainVO;
    }

    /**
     * 根据条件查找符合的列表
     *
     * @param callTaskLogListDTO 根据条件查找符合的列表
     * @return CallTaskLogVO  符合的批量外呼任务日志列表
     * @throws XbbException
     */
    @Override
    public CallTaskLogVO findDetails(CallTaskLogListDTO callTaskLogListDTO) throws XbbException {
        CallTaskLogVO callTaskLogVO = new CallTaskLogVO();
        Map<String, Object> params = new HashMap<>(16);
        params.put("corpid", callTaskLogListDTO.getCorpid());
        params.put("callTaskId", callTaskLogListDTO.getCallTaskId());
        if (callTaskLogListDTO.getTypeIn() != null) {
            params.put("typeIn", callTaskLogListDTO.getTypeIn());
        }
        if (callTaskLogListDTO.getStatusIn() != null) {
            params.put("statusIn", callTaskLogListDTO.getStatusIn());
        }
        params.put("del", DelEnum.NORMAL.getDel());
        List<CallTaskLogEntity> taskLogEntList = xbbCallTaskLogModel.findEntitys(params);

        if (taskLogEntList != null) {
            List<Long> cusId = new ArrayList<>();
            List<Long> conId = new ArrayList<>();
            for (CallTaskLogEntity callTaskLogEntity : taskLogEntList) {
                if (callTaskLogEntity.getCustomerId() != null) {
                    cusId.add(callTaskLogEntity.getCustomerId());
                }
                if (callTaskLogEntity.getContactId() != null) {
                    conId.add(callTaskLogEntity.getContactId());
                }
            }
            // 批量外呼日志来源（客户列表）  数据来源目前只是限定在客户列表或联系人列表
            if (cusId.size() != 0 && conId.size() == 0) {
                // 去重
                LinkedHashSet<Long> setCus = new LinkedHashSet<>(cusId);
                setCus.addAll(cusId);
                cusId.clear();
                cusId.addAll(setCus);
                LinkedHashMap<Long, String> cusMsg = new LinkedHashMap<>();
                List<CustomerEntityExt> customerExtList = customerService.getCustomerListByIds(callTaskLogListDTO.getCorpid(), cusId);
                if (customerExtList.size() != 0) {
                    for (CustomerEntityExt customerEntityExt : customerExtList) {
                        if (customerEntityExt.getData() == null) {
                            throw new XbbException(CustomerErrorCodeEnum.API_ERROR_201001);
                        } else {
                            cusMsg.put(customerEntityExt.getId(), customerEntityExt.getData().getString(CustomerManagementEnum.NAME.getAttr()));
                        }
                    }
                }
                for (CallTaskLogEntity taskLogEntity : taskLogEntList) {
                    taskLogEntity.setCustomerName(cusMsg.get(taskLogEntity.getCustomerId()));
                }
            } else if (conId.size() != 0 && cusId.size() != 0) {
                //批量外呼日志来源（联系人列表）
                //去重
                LinkedHashSet<Long> setCon = new LinkedHashSet<>(conId);
                setCon.addAll(conId);
                conId.clear();
                conId.addAll(setCon);
                LinkedHashMap<Long, String> conMsg = new LinkedHashMap<>();
                LinkedHashMap<Long, String> conCusMsg = new LinkedHashMap<>();
                List<ContactEntityExt> contactExtList = contactService.getContactListByIds(callTaskLogListDTO.getCorpid(), cusId);
                if (contactExtList.size() != 0) {
                    for (ContactEntityExt contactEntityExt : contactExtList) {
                        if (contactEntityExt.getData() == null) {
                            throw new XbbException(CustomerErrorCodeEnum.API_ERROR_201001);
                        } else {
                            conMsg.put(contactEntityExt.getId(), contactEntityExt.getData().getString(ContactEnum.NAME.getAttr()));
                            conCusMsg.put(contactEntityExt.getId(), contactEntityExt.getData().getString(ContactEnum.CUSTOMER_NAME.getAttr()));
                        }
                    }
                }
                for (CallTaskLogEntity taskLogEntity : taskLogEntList) {
                    taskLogEntity.setContactName(conMsg.get(taskLogEntity.getContactId()));
                    taskLogEntity.setCustomerName(conCusMsg.get(taskLogEntity.getContactId()));
                }
            }
        }
        PageHelper pageHelper = new PageHelper(callTaskLogListDTO.getPage(), callTaskLogListDTO.getPageSize());
        callTaskLogVO.setPageHelper(pageHelper);
        callTaskLogVO.setCallTaskLogList(taskLogEntList);
        return callTaskLogVO;
    }

    /**
     * 批量外呼计划日志单个删除
     *
     * @param callTaskLogDeleteDTO 批量外呼计划日志单个删除入参
     * @return CallTaskLogDeleteVO 批量外呼计划日志单个删除回参
     * @throws XbbException 销帮帮设定的异常
     * @author youli.chen
     * @version v1.0
     * @since v1.0
     */
    @Override
    public XbbResponse<CallTaskLogDeleteVO> delete(CallTaskLogDeleteDTO callTaskLogDeleteDTO) throws XbbException {
        CallTaskLogDeleteVO callTaskLogDeleteVO = new CallTaskLogDeleteVO();
        try {
            xbbCallTaskLogModel.deleteByKey(callTaskLogDeleteDTO.getCallTaskLogId(), callTaskLogDeleteDTO.getCorpid());
        } catch (Exception e) {
            throw new XbbException(CallCenterErrorCodeEnum.API_ERROR_301080);
        }
        return new XbbResponse<>(callTaskLogDeleteVO);
    }

    /**
     * 批量删除(结束上一次的批量外呼任务)
     *
     * @param callTaskLogBatchDeleteDTO 批量删除(结束上一次的批量外呼任务)入参
     * @return CallTaskLogBatchDeleteVO 批量删除(结束上一次的批量外呼任务)回参
     * @throws XbbException 销帮帮设定的异常
     * @author youli.chen
     * @version v1.0
     * @since v1.0
     */
    @Override
    public XbbResponse<CallTaskLogBatchDeleteVO> batchDelete(CallTaskLogBatchDeleteDTO callTaskLogBatchDeleteDTO) throws XbbException {
        CallTaskLogBatchDeleteVO batchDeleteVO = new CallTaskLogBatchDeleteVO();
        String corpid = callTaskLogBatchDeleteDTO.getCorpid();
        Long callTaskId = callTaskLogBatchDeleteDTO.getCallTaskId();
        xbbCallTaskLogModel.batchDelete(corpid, callTaskId);
        Integer useTaskCount = taskFactNum(corpid, callTaskId);
        taskEnd(callTaskId, corpid, useTaskCount);
        return new XbbResponse<>(batchDeleteVO);
    }

    /**
     * 获取下一个需要拨打的号码(模糊查询出号码明文)
     *
     * @param callTaskLogFindNextPhoneDTO 获取下一个需要拨打的号码(模糊查询出号码明文)入参
     * @return CallTaskLogFindNextPhoneVO 获取下一个需要拨打的号码(模糊查询出号码明文)回参
     * @throws XbbException 销帮帮设定的异常
     * @author youli.chen
     * @version v1.0
     * @since v1.0
     */
    @Override
    public XbbResponse<CallTaskLogFindNextPhoneVO> findNextPhone(CallTaskLogFindNextPhoneDTO callTaskLogFindNextPhoneDTO) throws XbbException {
        CallTaskLogFindNextPhoneVO callTaskLogFindNextPhoneVO = new CallTaskLogFindNextPhoneVO();
        String corpid = callTaskLogFindNextPhoneDTO.getCorpid();
        Long callTaskId = callTaskLogFindNextPhoneDTO.getCallTaskId();
        Map<String, Object> params = new HashMap<>(16);
        params.put("corpid", corpid);
        params.put("callTaskId", callTaskId);
        params.put("del", DelEnum.NORMAL.getDel());
        params.put("phoneStatus", "xbbCall");
        List<CallTaskLogEntity> taskLogEntList = xbbCallTaskLogModel.findEntitys(params);
        CallTaskLogEntity callTaskLogEntity = taskLogEntList.size() > 0 ? taskLogEntList.get(0) : null;
        String msg = null;
        if (callTaskLogEntity != null) {
            String callTaskLogPhone = callTaskLogEntity.getPhone();
            if (callTaskLogEntity.getCustomerId() != null && callTaskLogEntity.getContactId() == null) {
                CustomerEntityExt customerEntityExt = customerModel.getByKey(callTaskLogEntity.getCustomerId(),
                        callTaskLogEntity.getCorpid());
                if (customerEntityExt == null || customerEntityExt.getData() == null) {
                    throw new XbbException(CustomerErrorCodeEnum.API_ERROR_201001);
                } else {
                    String cusPhone = customerEntityExt.getData().getString(CustomerManagementEnum.PHONE.getAttr());
                    if (StringUtil.isNotEmpty(cusPhone)) {
                        JSONArray phoneJsonArray;
                        try {
                            phoneJsonArray = JSONArray.parseArray(cusPhone);
                        } catch (Exception e) {
                            throw new XbbException(CallCenterErrorCodeEnum.API_ERROR_301081);
                        }
                        msg = phoneFormat(phoneJsonArray, callTaskLogPhone);
                    }
                }
            } else if (callTaskLogEntity.getContactId() != null && callTaskLogEntity.getCustomerId() != null) {
                ContactEntityExt contactEntityExt =
                        contactModel.getByKey(callTaskLogEntity.getContactId(), callTaskLogEntity.getCorpid());
                if (contactEntityExt == null || contactEntityExt.getData() == null) {
                    throw new XbbException(CustomerErrorCodeEnum.API_ERROR_201001);
                } else {
                    String conPhone = contactEntityExt.getData().getString(CustomerManagementEnum.PHONE.getAttr());
                    JSONArray phoneJsonArray;
                    try {
                        phoneJsonArray = JSONArray.parseArray(conPhone);
                    } catch (Exception e) {
                        throw new XbbException(CallCenterErrorCodeEnum.API_ERROR_301082);
                    }
                    msg = phoneFormat(phoneJsonArray, callTaskLogPhone);
                }
            }
        } else {
            Integer useTaskCount = taskFactNum(corpid, callTaskId);
            Integer result = taskEnd(callTaskId, corpid, useTaskCount);
            if (result > 0) {
                msg = I18nMessageUtil.getMessage(I18nStringConstant.BATCH_OUTBOUND_CALL_END);
            }
        }
        callTaskLogFindNextPhoneVO.setPhone(msg);
        return new XbbResponse<>(callTaskLogFindNextPhoneVO);
    }

    /**
     * 客户状态筛选
     *
     * @param callSearchItemsDTO 客户状态筛选入参
     * @return CallSearchItemsVO 客户状态筛选回参
     * @throws XbbException 销帮帮设定的异常
     * @author youli.chen
     * @version v1.0
     * @since v1.0
     */
    @Override
    public XbbResponse<CallSearchItemsVO> searchItems(CallSearchItemsDTO callSearchItemsDTO) throws XbbException {
        CallSearchItemsVO callSearchItemsVO = new CallSearchItemsVO();
        List<ItemPoJo> itemPoJoList = dictionaryService.getArrayList(DictionaryEnum.CUSTOMER_STATUS,
                callSearchItemsDTO.getCorpid(), null);
        callSearchItemsVO.setStatus(itemPoJoList);
        return new XbbResponse<>(callSearchItemsVO);
    }

    /**
     * 号码格式化提取
     *
     * @param phoneJsonArray   json格式的电话数据，来源：客户，联系人
     * @param callTaskLogPhone 联系方式
     * @return
     */
    private String phoneFormat(JSONArray phoneJsonArray, String callTaskLogPhone) {
        String msg = null;
        if (callTaskLogPhone == null) {
            msg = I18nMessageUtil.getMessage(I18nStringConstant.CURRENT_NUMBER_EMPTY);
        } else {
            Integer indexLog = callTaskLogPhone.indexOf(XbbCallTaskLogConstant.BRACKETS);
            if (indexLog != -1 && callTaskLogPhone.indexOf(XbbCallTaskLogConstant.REVERSE_BRACKETS) != -1) {
                String phone = callTaskLogPhone.substring(indexLog + 1,
                        callTaskLogPhone.lastIndexOf(XbbCallTaskLogConstant.REVERSE_BRACKETS));
                if (phoneJsonArray != null && phoneJsonArray.size() > 0) {
                    for (int i = 0; i < phoneJsonArray.size(); i++) {
                        String tel = (String) phoneJsonArray.getJSONObject(i).get("text_2");
                        if (phone.length() > 7) {
                            if (tel.substring(0, 3).equals(phone.substring(0, 3)) &&
                                    tel.substring(tel.length() - 4, tel.length()).equals(phone.substring(phone.length() - 4, phone.length()))) {
                                msg = tel;
                            }
                        } else {
                            msg = phone;
                        }
                    }
                }
            }
        }
        return msg;
    }

    /**
     * 统计单个任务实际使用的批量外呼条数
     *
     * @author youli.chen
     */
    private Integer taskFactNum(String corpid, Long callTaskId) throws XbbException {
        Map<String, Object> paramsUse = new LinkedHashMap<>(16);
        paramsUse.put("corpid", corpid);
        paramsUse.put("callTaskId", callTaskId);
        paramsUse.put("del", DelEnum.NORMAL.getDel());
        paramsUse.put("countStatus", "allUse");
        Integer useTaskCount = xbbCallTaskLogModel.getEntitysCount(paramsUse);
        return useTaskCount;
    }

    /**
     * 批量外呼任务结束
     *
     * @author youli.chen
     */
    private Integer taskEnd(Long key, String corpid, Integer useTaskCount) throws XbbException {
        CallTaskEntity getDetailById = xbbCallTaskModel.getDetailById(key, corpid);
        if (getDetailById == null) {
            throw new XbbException(CallCenterErrorCodeEnum.API_ERROR_301083);
        }
        getDetailById.setStatus(1);
        getDetailById.setTaskFactNum(useTaskCount);
        Integer result = xbbCallTaskModel.update(getDetailById);
        return result;
    }

    /**
     * 业务层 获取每个通话状态对应的总条数数据封装
     *
     * @param taskLogEntList 单个任务对应的任务日志
     * @return
     */
    private CallTaskLogCountVO taskLogCountMsg(List<CallTaskLogEntity> taskLogEntList) {
        CallTaskLogCountVO countVO = new CallTaskLogCountVO();
        List<Long> cusId = new ArrayList<>();
        int normal = 0;
        int notAnswering = 0;
        int incomingCallBarring = 0;
        int hungUp = 0;
        int onThePhone = 0;
        int netBusy = 0;
        int powerOff = 0;
        int phoneNullOrStop = 0;
        int phoneError = 0;
        int unKnown = 0;
        //消耗的条数
        countVO.setUseTaskLogCount(taskLogEntList.size());
        for (CallTaskLogEntity taskLogEntity : taskLogEntList) {
            cusId.add(taskLogEntity.getCustomerId());
            if (taskLogEntity.getStatus() == null) {
                continue;
            }
            if (taskLogEntity.getStatus().equals(CallStatusEnum.NORMAL.getCode())) {
                normal += 1;
            } else if (taskLogEntity.getStatus().equals(CallStatusEnum.NOT_ANSWERING.getCode())) {
                notAnswering += 1;
            } else if (taskLogEntity.getStatus().equals(CallStatusEnum.INCOMING_CALL_BARRING.getCode())) {
                incomingCallBarring += 1;
            } else if (taskLogEntity.getStatus().equals(CallStatusEnum.HUNG_UP.getCode())) {
                hungUp += 1;
            } else if (taskLogEntity.getStatus().equals(CallStatusEnum.ON_THE_PHONE.getCode())) {
                onThePhone += 1;
            } else if (taskLogEntity.getStatus().equals(CallStatusEnum.NET_BUSY.getCode())) {
                netBusy += 1;
            } else if (taskLogEntity.getStatus().equals(CallStatusEnum.POWER_OFF.getCode())) {
                powerOff += 1;
            } else if (taskLogEntity.getStatus().equals(CallStatusEnum.PHONE_NULL_OR_STOP.getCode())) {
                phoneNullOrStop += 1;
            } else if (taskLogEntity.getStatus().equals(CallStatusEnum.PHONE_ERROR.getCode())) {
                phoneError += 1;
            } else {
                unKnown += 1;
            }
        }

        //正常总条数
        countVO.setNormal(normal);
        //无人接听总条数
        countVO.setNotAnswering(notAnswering);
        //呼入限制总条数
        countVO.setIncomingCallBarring(incomingCallBarring);
        //被挂断总条数
        countVO.setHungUp(hungUp);
        //通话中总条数
        countVO.setOnThePhone(onThePhone);
        //网络忙总条数
        countVO.setNetBusy(netBusy);
        //关机总条数
        countVO.setPowerOff(powerOff);
        //空号或停机总条数
        countVO.setPhoneNullOrStop(phoneNullOrStop);
        //号码异常总条数
        countVO.setPhoneError(phoneError);
        //未知总条数
        countVO.setUnKnown(unKnown);
        //去重
        LinkedHashSet<Long> set = new LinkedHashSet<>(cusId);
        set.addAll(cusId);
        cusId.clear();
        cusId.addAll(set);
        //客户数量
        countVO.setCustomerCount(cusId.size());
        return countVO;
    }


    /**
     * 联系方式脱敏处理
     *
     * @param phone             客户或联系人的json联系方式
     * @param callTaskLogEntity 批量外呼计划日志 实体
     * @return
     */
    private CallTaskLogEntity callTaskLogPhone(String phone, CallTaskLogEntity callTaskLogEntity) throws XbbException {
        if (StringUtil.isEmpty(phone)) {
            callTaskLogEntity.setPhone(phone);
            return callTaskLogEntity;
        }

        JSONArray phoneJsonArray;
        try {
            phoneJsonArray = JSONArray.parseArray(phone);
        } catch (Exception e) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100033);
        }
        if (phoneJsonArray == null || phoneJsonArray.size() == 0) {
            callTaskLogEntity.setPhone(phone);
            return callTaskLogEntity;
        }

        for (int i = 0; i < phoneJsonArray.size(); i++) {
            String tel = (String) phoneJsonArray.getJSONObject(i).get("text_2");
            String msg;
            String num;
            if (StringUtil.isEmpty(tel)) {
                msg = tel;
            } else {
                //敏感数据脱敏处理 加密
                if (tel.length() > 7) {
                    num = tel.substring(0, 3) + "****" + tel.substring(tel.length() - 4, tel.length());
                    msg = phoneJsonArray.getJSONObject(i).get("text_1") + "(" + num + ")";
                } else {
                    msg = phoneJsonArray.getJSONObject(i).get("text_1") + "(" + tel + ")";
                }
            }
            callTaskLogEntity.setPhone(msg);
        }
        return callTaskLogEntity;
    }
}
